{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2  \n",
    "import numpy as np  \n",
    "import matplotlib.pyplot as plt  \n",
    "from PIL import Image  \n",
    "import os  \n",
    "\n",
    "plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 设置字体为微软雅黑\n",
    "source_img = cv2.imread('C:/Users/86178/Desktop/hanzi1.jpg')  # 使用cv2打开源图像\n",
    "gray_img = cv2.cvtColor(source_img, cv2.COLOR_BGR2GRAY)  # 使用cv2将源图像转换为灰度图\n",
    "threshold_val = 128  # 设定阈值\n",
    "# 使用cv2.threshold将灰度图转换为二值图\n",
    "_, binary_img = cv2.threshold(gray_img, threshold_val, 255, cv2.THRESH_BINARY)\n",
    "# 使用cv2.bitwise_not来实现黑白颜色的互换\n",
    "binary_img = cv2.bitwise_not(binary_img)\n",
    "# 将二值图转换为numpy数组以便使用opencv处理\n",
    "opencv_img = np.array(binary_img)\n",
    "# 定义结构元素\n",
    "structuring_element = np.ones((5, 5), np.uint8)\n",
    "# 使用腐蚀操作\n",
    "eroded_img = cv2.erode(opencv_img, structuring_element, iterations=4)\n",
    "# 使用膨胀操作\n",
    "dilated_img = cv2.dilate(eroded_img, structuring_element, iterations=8)\n",
    "# 使用中值滤波\n",
    "filtered_img = cv2.medianBlur(dilated_img, 27)\n",
    "# 使用闭运算\n",
    "closed_img = cv2.morphologyEx(filtered_img, cv2.MORPH_CLOSE, structuring_element, iterations=50)\n",
    "# 使用高斯模糊\n",
    "blurred_img = cv2.GaussianBlur(closed_img, (5, 5), 0)\n",
    "# 使用Canny边缘检测，手动定义上下阈值\n",
    "lower = 50\n",
    "upper = 200\n",
    "edges_detected = cv2.Canny(blurred_img, lower, upper)\n",
    "# 找到图像中的轮廓  \n",
    "contours, _ = cv2.findContours(edges_detected, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  \n",
    "  \n",
    "img_with_contours = cv2.cvtColor(source_img, cv2.COLOR_BGR2RGB) \n",
    "  \n",
    "for idx, single_contour in enumerate(contours):  \n",
    "    posX, posY, width, height = cv2.boundingRect(single_contour)  \n",
    "    border = 40  \n",
    "    posX = max(0, posX - border)  \n",
    "    width = width + 2 * border  \n",
    "    height = height + border  \n",
    "    cv2.rectangle(img_with_contours, (posX, posY), (posX + width, posY + height), (0, 255, 0), 2)  \n",
    "  \n",
    "axs[0].imshow(gray_img, cmap='gray')\n",
    "axs[0].set_title('灰度图', size=15)\n",
    "axs[0].axis('off')\n",
    "axs[1].imshow(binary_img, cmap='gray')\n",
    "axs[1].set_title('二值图', size=15)\n",
    "axs[1].axis('off')\n",
    "axs[2].imshow(eroded_img, cmap='gray')\n",
    "axs[2].set_title('腐蚀图', size=15)\n",
    "axs[2].axis('off')  \n",
    "axs[3].imshow(filtered_img, cmap='gray')  # 修复了这里的换行符问题  \n",
    "axs[3].set_title('中值滤波图', size=15)  # 修改了标题以更好地描述图像  \n",
    "axs[3].axis('off')  \n",
    "axs[4].imshow(closed_img, cmap='gray')\n",
    "axs[4].set_title('闭运算图', size=15)\n",
    "axs[4].axis('off')\n",
    "axs[5].imshow(edges_detected, cmap='gray')\n",
    "axs[5].set_title('Canny边缘检测', size=15)\n",
    "axs[5].axis('off') \n",
    "axs[6].imshow(cv2.cvtColor(img_with_contours, cv2.COLOR_BGR2RGB))  \n",
    "axs[6].set_title('带有轮廓的图像', size=15)  \n",
    "axs[6].axis('off')  \n",
    "  \n",
    "plt.show()\n",
    "\n",
    "\n",
    "from pathlib import Path  \n",
    "  \n",
    "path = Path('chars')  \n",
    "if not path.exists():  \n",
    "    path.mkdir(parents=True, exist_ok=True)  # 创建目录，如果已存在则不会报错\n",
    "for single_contour in contours:  \n",
    "    posX, posY, width, height = cv2.boundingRect(single_contour)  # 计算轮廓的边界框\n",
    "    border = 40  # 设定边界\n",
    "    posX = max(0, posX - border)  # 计算新的x坐标\n",
    "    width = width + 2 * border  # 计算新的宽度\n",
    "    height = height + border  # 计算新的高度\n",
    "    # 裁剪出字符图像\n",
    "    single_char_img = gray_img[posY:posY + height, posX:posX + width]\n",
    "    # 将numpy数组转换为PIL的Image对象\n",
    "    single_char_img_pil = Image.fromarray(single_char_img)\n",
    "    cv2.imwrite(f'chars/char_{idx}.png', single_char_img)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
